package com.simple.editor.action.impl;

import com.simple.editor.ApplicationContext;
import com.simple.editor.action.EditorException;
import com.simple.editor.callback.Callback;
import com.simple.editor.callback.DefaultUICallbackImpl;
import com.simple.editor.converter.FileModelConverter;
import com.simple.editor.ui.ChangesPane;
import com.simple.editor.ui.FileModel;
import com.simple.editor.ui.InfoPane;
import com.simple.editor.ui.TabbedEditorPane;
import com.simple.editor.vcs.VcsClient;
import com.simple.editor.vcs.VcsClientRegistry;
import com.simple.editor.vcs.VcsFile;

import java.util.Map;

/**
 * {@link SaveEditorUIAction} handles user "Save File" action.
 * <p/>
 * Created with IntelliJ IDEA.
 * User: vsoroka
 * Date: 05.06.13
 * Time: 17:22
 * To change this template use File | Settings | File Templates.
 */
public class SaveEditorUIAction extends AbstracEditorUIAction {

    private final ApplicationContext ctx;
    private final InfoPane infoPane;
    private final TabbedEditorPane editorPane;
    private final ChangesPane changesPane;
    private final VcsClientRegistry vcsClientRegistry;

    public SaveEditorUIAction(final ApplicationContext ctx, final InfoPane infoPane, final TabbedEditorPane editorPane,
                              final ChangesPane changesPane, final VcsClientRegistry vcsClientRegistry) {
        this.ctx = ctx;
        this.infoPane = infoPane;
        this.editorPane = editorPane;
        this.changesPane = changesPane;
        this.vcsClientRegistry = vcsClientRegistry;
    }

    @Override
    public void perform(final FileModel... files) throws EditorException {
        perform(new DefaultUICallbackImpl(), files);
    }

    @Override
    public void perform(final Callback uiCallback, final FileModel... files) throws EditorException {

        uiCallback.onStart();

        final FileModel[] savedFiles;
        if (files != null && files.length > 0) {
            savedFiles = files;
            editorPane.saveTab(files);
        } else {
            // Save All action
            savedFiles = editorPane.saveAllTabs();
        }

        changesPane.refreshTree();
        final Map<String, VcsFile> vcsFilesMap = FileModelConverter.convertFiles(savedFiles);
        final VcsClient vcsClient = vcsClientRegistry.getCurrentVcsClient();

        // Refresh file status
        vcsClient.refreshStatus(new RefreshActionUICallbackImpl(vcsFilesMap, infoPane, ctx, savedFiles) {
            @Override
            public void onComplete() {
                super.onComplete();
                uiCallback.onComplete();
            }

            @Override
            public void onFailure(Exception ex) {
                super.onFailure(ex);
                uiCallback.onFailure(ex);
            }
        }, vcsFilesMap.values());
    }
}

